package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class ViewCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        Account account = (Account)session.getAttribute("account");
        String hasViewedCart = null;
        if(account!=null)hasViewedCart = (String) session.getAttribute("hasViewedCart");

        if(cart!=null&&account!=null&&hasViewedCart==null)
        {
            session.setAttribute("hasViewedCart","yes");

            Iterator<CartItem>cartItems = cart.getAllCartItems();
            while (cartItems.hasNext())
            {
                CartItem cartItem = cartItems.next();
                String itemId = cartItem.getItem().getItemId();
                CatalogService.insertCart(account,itemId);
            }
            cart = null;
        }


        if(cart == null)
        {
            cart = new Cart();
        }



        if(account!=null&&hasViewedCart==null)
        {
            cart = CatalogService.addCart(account,cart);
            session.setAttribute("hasViewedCart","yes");
            hasViewedCart = "yes";
        }
        session.setAttribute("cart",cart);

        req.getRequestDispatcher(VIEW_CART).forward(req,resp);
    }
}
